<template>
    <div class="container">
        <Collapse :bordered="true" :defaultActiveKey="['1']">
            <CollapsePanel header="数据列表" key="1">
                <div class="operation">
                    <Button class="button" v-for="(item, index) in buttons"
                            :key="index" @click="click(item.buttonType, item.path, item.openMethod)" :style="item.color ? 'background-color:'+item.color : ''">
                        <span v-html="item.icon"></span>
                        <span>{{item.name}}</span>
                    </Button>
                </div>
                <Table :row-selection="rowSelection()"
                       :dataSource="data"
                       :columns="columns"
                       :pagination="pagination"
                       :rowKey="rowKey"
                       :scroll="data.length > 0 &&
                        columns.length > 5 ? {x: columns.length*5 + '%', y: true} : ''"
                       :loading="false" />
            </CollapsePanel>
        </Collapse>
    </div>
</template>
<script>
    import {Table, Collapse, CollapsePanel, Button, message, Modal} from "ant-design-vue";
    import {Base64} from 'js-base64'
    export default {
        name: 'table',
        data(){
            return{
                selectedRowKeys: [],
                id: '',
                buttons: [],
            }
        },
        props: {
            columns: {
                type: Array,
                default: []
            },
            pagination: {
                type: Object,
                default: {
                    current: 1,
                    pageSize: 10
                }
            },
            data: {
                type: Array,
                default: []
            },
            rowKey: {
                default: 'id',
                type: String
            }
        },
        components: {
            Table,
            Collapse,
            CollapsePanel,
            Button,
        },
        mounted(){
            this._loadButton();
        },
        methods: {
            rowSelection(){
                return {
                    selectedRowKeys: this.selectedRowKeys,
                    onChange: (selectedRowKeys, selectedRows) => {
                      this.selectedRowKeys = selectedRowKeys;
                    }
                }
            },

            /**
             * 加载按钮
             */
            _loadButton(){
                const query = this.$route.query;
                this.id = JSON.parse(Base64.decode(Object.keys(query)
                    .map(item => query[item]).join(""))).id;
                const menus = this.$store.state.menus;
                menus.forEach(item => {
                    const buttons = item.children.filter(s => s.id == this.id).map(s => s.children || []).flat();
                    buttons.length > 0 && (this.buttons = buttons);
                })
            },

            click(type, path, openMethod){
                switch (type) {
                    case 'add': return this.add(path, openMethod);
                    case 'modify': return this.modify(path, openMethod);
                    case 'delete' : return this.remove();
                    case 'details': return this.details(path, openMethod);
                }
            },

            /**
             * 跳转路由
             */
            details(path, openMethod){
                this._validateSelectedRows(false).then(()=>{
                    path ? this._go(path, openMethod) : this.$parent.details(this.selectedRowKeys);
                }).catch(e => {
                    console.error(e);
                    message.error(e);
                })
            },

            /**
             * 添加
             */
            add(path, openMethod){
                this.selectedRowKeys = [];
                path ? this._go(path, openMethod) : this.$parent.add();
            },

            /**
             * 修改
             */
            modify(path, openMethod){
                this._validateSelectedRows(false).then(()=>{
                    path ? this._go(path, openMethod) : this.$parent.modify(this.selectedRowKeys);
                }).catch(e => {
                    console.error(e);
                    message.error(e);
                })

            },

            /**
             * 删除
             */
            remove(){
                const self = this;
                this._validateSelectedRows().then(()=>{
                    Modal.confirm({
                        title: '确定要删除数据么？',
                        okText: '确认',
                        cancelText: '取消',
                        onOk() {
                            self.$parent.delete(self.selectedRowKeys).then(res => {
                                if(res){
                                    message.success('删除成功')
                                    self.selectedRowKeys = []
                                }
                            }).catch(e => {
                                console.error(e);
                            });

                        }
                    })
                }).catch(e => {
                    console.error(e);
                    message.error(e);
                })
            },

            /**
             * 选择条数检查
             */
            _validateSelectedRows(single = true){
                return new Promise((resolve, reject) => {
                    if(this.selectedRowKeys.length == 0){
                        return reject("至少要选择一条数据")
                    }
                    if(!single && this.selectedRowKeys.length > 1){
                        return reject("只能选择一条数据进行编辑")
                    }
                    return resolve();
                })
            },

            /**
             * 跳转
             */
            _go(path, openMethod){
                const param = this.selectedRowKeys.length > 0 ? {query:
                        Base64.encode(JSON.stringify({id: this.selectedRowKeys.join(",")}))} : "";
                if(openMethod && openMethod === '1'){
                    console.log(param)
                    let route = this.$router.resolve({path: path, ...param});
                    window.open(route.href, '_blank');
                }else {
                    this.$router.push({path: path, ...param});
                }
            },
        }
    }
</script>
<style scoped lang="scss">

</style>
